package com.ruoyi.ftrl.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ftrl.domain.CommunityMeasurement;
import com.ruoyi.ftrl.domain.Dto.RealDataDTO;
import com.ruoyi.ftrl.domain.RealTimeData;
import com.ruoyi.ftrl.service.IRealTimeDataService;
import com.ruoyi.ftrl.service.impl.CommunityMappingService;
import com.ruoyi.ftrl.service.impl.DataProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/data/realtime")
@Api(tags = "实时数据接入")
public class RealDataController {
    @Autowired
    IRealTimeDataService realTimeDataService;
    @Anonymous
    @PostMapping("/receive")
    @ApiOperation("接收实时数据")
    public AjaxResult receiveRealData(@RequestBody RealDataDTO realDataDTO) {
        // 日志记录接收到的数据
        log.error("接收到实时数据: {}", realDataDTO);

        // 数据校验
        if (realDataDTO == null || StringUtils.isEmpty(realDataDTO.getTime())) {
            log.error("接收的数据不合法");
            return AjaxResult.error("数据不合法");
        }

        try {
            // 处理数据的业务逻辑
            processRealData(realDataDTO);

            return AjaxResult.success("数据接收成功");
        } catch (Exception e) {
            log.error("处理实时数据发生异常", e);
            return AjaxResult.error("数据处理失败");
        }
    }

    private void processRealData(RealDataDTO realDataDTO) {
        // 1. 可以进行数据持久化
        // 2. 可以触发后续业务流程
        // 3. 可以进行数据转换或分析
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 根据实际时间格式调整

        // 示例：打印每个数据项
        if (realDataDTO.getData() != null) {
            realDataDTO.getData().forEach(item -> {
                log.error("处理数据项: ID={}, 值={}", item.getId(), item.getValue());

                // 创建 RealTimeData 对象
                RealTimeData realTimeData = new RealTimeData();

                Date timestamp = null;
                try {
                    timestamp = dateFormat.parse(realDataDTO.getTime());
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                realTimeData.setTimestamp(timestamp);
                realTimeData.setSn(realDataDTO.getSn());
                realTimeData.setDataType(realDataDTO.getType());
                realTimeData.setDataItemId(item.getId());
                realTimeData.setDescription(item.getDesc());
                realTimeData.setQuality(Integer.valueOf(item.getQuality()));
                realTimeData.setValue(item.getValue());
                realTimeData.setCreatedBy("admin"); // 或者根据实际情况设置
                realTimeData.setCreatedAt(new Date());
//                realTimeData.setUpdatedBy("admin");
//                realTimeData.setUpdatedAt(new Date());
                realTimeData.setRemarks("接收到的实时数据");
                realTimeData.setReservedField(""); // 根据需要设置
                realTimeData.setIsLatest(1);
                // 持久化数据
                realTimeDataService.insertRealTimeData(realTimeData);
            });
        }
    }

    /**
     * 数据统一化展示
     */
    @Autowired
    private CommunityMappingService communityMappingService;

    @GetMapping("/processed")
    @ApiOperation("获取处理后的数据")
    public AjaxResult getProcessedData() {
        List<RealTimeData> realTimeDataList = realTimeDataService.selectAllRealTimeData(); // 获取所有实时数据
        DataProcessor dataProcessor = new DataProcessor(communityMappingService);
        List<CommunityMeasurement> processedData = dataProcessor.processData(realTimeDataList);
        return AjaxResult.success(processedData);
    }

}


